package com.wssnail.xss.utils;


import com.wssnail.xss.annotation.StringEscapeCode;
import org.apache.commons.text.StringEscapeUtils;

import java.lang.reflect.Field;

/**
 * @author 熟透的蜗牛
 * @version 1.0
 * @description: 配置字符串格式文本处理工具
 * @date 2023/8/14 23:50
 */
public class StringEscapeCodeUtil {

    public static void unStringEscape(Class<?> clazz, Object obj) throws IllegalAccessException {
        StringEscapeCode declaredAnnotation = clazz.getDeclaredAnnotation(StringEscapeCode.class);
        if (declaredAnnotation != null) {
            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                if (fields[i].getGenericType().toString().endsWith("String")) {
                    //有注解，设置字段
                    fields[i].setAccessible(true);
                    String value = StringEscapeUtils.unescapeHtml4((String) fields[i].get(obj));
                    fields[i].set(obj, value);
                }
            }
        } else {
            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                StringEscapeCode annotation = fields[i].getAnnotation(StringEscapeCode.class);
                if (fields[i].getGenericType().toString().endsWith("String")) {
                    if (annotation != null) {
                        //有注解，设置字段
                        fields[i].setAccessible(true);
                        String value = StringEscapeUtils.unescapeHtml4((String) fields[i].get(obj));
                        fields[i].set(obj, value);
                    }
                }
            }
        }
    }
}
